#! /usr/bin/python
# -*- coding: utf-8 -*-

from flask import Flask, jsonify,render_template, request,send_from_directory,url_for,redirect
from flask_cors import CORS

import json
from datetime import timedelta
import time
from grpc_clt import *

rpcClient = grpcClient()
# configuration
DEBUG = True
DEMO = False
MAX_DISPLAY=1000

# instantiate the app
app = Flask(__name__,static_folder = "./dist/static", template_folder = "./dist")
app.config.from_object(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT']=timedelta(seconds=1)

# enable CORS
CORS(app, resources={r'/*': {'origins': '*'}})


@app.route('/',methods=['GET']) 
def index(): 
    return render_template("index.html")

# sanity check route
@app.route('/ping', methods=['GET'])
def ping_pong():
    return jsonify('pong!')



@app.route('/test', methods=['GET'])
def test():
	p = request.args.get('p')
	name = request.args.get('name')
	v_dict = {}
	v_dict['param_p'] = p
	if name:
		v_dict['param_name'] = name
	return json.dumps(v_dict)

@app.route("/data", methods=['GET'])
def download_file():
    print("start download file")
    # 此处的filepath是文件的路径，但是文件必须存储在static文件夹下， 比如images\test.jpg
    #return app.send_static_file("plate_data.csv") 
    # dirpath="/home/baosteel/mydev/test/webapp/dist/static"
    # filename="plate_data.csv"
    # return send_from_directory(dirpath, filename, as_attachment=True) 
    tm_now=int(time.mktime(time.localtime()))
    #str_url = "download?timestamp={}".format(tm_now)
    str_url = "download"
    #print("url",str_url)
    #return redirect(url_for(str_url))
    #return url_for(str_url,timestamp=tm_now)
    return redirect(url_for(str_url,timestamp=tm_now))
    
    #str_url = "http://127.0.0.1:20080/download?timestamp={}".format(tm_now)
    #return redirect(str_url)

@app.route("/download",methods=['GET'])
def download():
    dirpath="/home/baosteel/mydev/test/webapp/dist/static"
    filename="plate_data.csv"
    return send_from_directory(dirpath, filename, as_attachment=True) 


@app.route('/getplateset', methods=['GET'])
def GetPlateSetData():
    v_dict = {}

    if DEMO:
        
        v_plate = {}
        v_plate["plate_id"]="12345600001"
        v_plate["material_id"]="123456"
        v_plate["steel_grade"]="SUS304"
        v_plate["length"]=10000
        v_plate["width"] = 1830
        v_plate["thickness"]=2.6
        v_plate["temp"]=37.82
        v_plate["set_inlet"]=-3.1
        v_plate["set_outlet"]=2.7
        v_plate["set_flextion"]=-1.2
        v_plate["full_length"]=2.1596
        v_plate["full_cross"]=2.863
        v_plate["cross_1m"]=1.781
        v_plate["length_1m"]=2.01
        v_plate["length_2m"]=1.978
        v_dict['pre'] = v_plate
        v_plate2 = v_plate.copy()

        v_plate2["plate_id"]="12345600002"
        v_plate2["temp"]=33.79
        v_plate2["full_length"]=0
        v_plate2["full_cross"]=0
        v_plate2["cross_1m"]=0
        v_plate2["length_1m"]=0
        v_plate2["length_2m"]=0
        v_dict['cur']=v_plate2
        
    else:
        ret = rpcClient.GetPlateSetData()
        # print("recv ret: ", ret)
        if ret:
            key_nms = ["cur","pre"]
            idx = 0
            for _it in ret.set:
                v_plate = {}
                v_plate["plate_id"]=_it.plate_id
                v_plate["material_id"]=_it.material_id
                v_plate["steel_grade"]=_it.steel_grade
                v_plate["length"]=round(_it.length,3)
                v_plate["width"] = round(_it.width,3)
                v_plate["thickness"]=round(_it.thickness,3)
                v_plate["temp"]=round(_it.temp,2)
                v_plate["set_inlet"]=round(_it.set_inlet,3)
                v_plate["set_outlet"]=round(_it.set_outlet,3)
                v_plate["set_flextion"]=round(_it.set_flextion,3)
                v_plate["full_length"]=round(_it.full_length,3)
                v_plate["full_cross"]=round(_it.full_cross,3)
                v_plate["cross_1m"]=round(_it.cross_1m,3)
                v_plate["length_1m"]=round(_it.length_1m,3)
                v_plate["length_2m"]=round(_it.length_2m,3)
                v_dict[key_nms[idx]] = v_plate.copy()
                #print("{}:{}".format(key_nms[idx],v_plate["plate_id"]))
                idx += 1
                if idx>1:
                    break

    return json.dumps(v_dict)

@app.route('/getplateact', methods=['GET'])
def GetPlateActData():
    time_from = request.args.get("from")
    time_to = request.args.get("to")
    print("time: {} , {}".format(time_from, time_to))
    v_dict = {}
    v_list = []
    
    if DEMO:
        
        v_plate = {}
        v_plate["plate_id"]="12345600000"
        v_plate["pred_full_length"]=1.9792
        v_plate["pred_full_cross"] = 2.0071
        v_plate["meas_full_length"] = 2.6832
        v_plate["meas_full_cross"] = 2.3792
        v_plate["timestamp"]="2020-01-10 14:59:32"
        v_list.append(v_plate.copy())
        #v_dict["plate1"]=v_plate.copy()
        v_plate["plate_id"]="12345600001"
        v_plate["pred_full_length"]=3.6702
        v_plate["pred_full_cross"] = 3.271
        v_plate["meas_full_length"] = 2.9832
        v_plate["meas_full_cross"] = 3.3792
        v_plate["timestamp"]="2020-01-10 15:05:12"
        v_list.append(v_plate.copy())
        # v_dict["plate"]=v_list
        
    
    else:

        ret = rpcClient.GetPlateActData(time_from, time_to)

        if ret:
            idx = 0
            for _it  in ret.act:
                v_plate={}
                v_plate["plate_id"] = _it.plate_id
                v_plate["steel_grade"] = _it.steel_grade
                
                v_plate["length"]=round(_it.length,3)
                v_plate["width"] = round(_it.width,3)
                v_plate["thickness"]=round(_it.thickness,3)
                v_plate["temp"]=round(_it.temp,2)

                v_plate["set_inlet_usr"]=round(_it.set_inlet_usr,3)
                v_plate["set_outlet_usr"]=round(_it.set_outlet_usr,3)
                v_plate["set_flextion_usr"]=round(_it.set_flextion_usr,3)
                v_plate["set_inlet_mod"]=round(_it.set_inlet_mod,3)
                v_plate["set_outlet_mod"]=round(_it.set_outlet_mod,3)
                v_plate["set_flextion_mod"]=round(_it.set_flextion_mod,3)

                v_plate["pred_full_length"]=round(_it.pred_full_length,3)
                v_plate["pred_full_cross"]=round(_it.pred_full_cross,3)
                v_plate["meas_full_length"]=round(_it.meas_full_length,3)
                v_plate["meas_full_cross"]=round(_it.meas_full_cross,3)
                v_plate["meas_cross_1m"]=round(_it.meas_cross_1m,3)
                v_plate["meas_length_1m"]=round(_it.meas_length_1m,3)
                v_plate["meas_length_2m"]=round(_it.meas_length_2m,3)
                
                v_plate["full_length_limit"]=round(_it.full_length_limit,3)
                v_plate["full_cross_limit"]=round(_it.full_cross_limit,3)
                
                v_plate["timestamp"]= time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(_it.timestamp))



                #print("{},tm:{},fl:{},{},fc:{},{}".format(v_plate["plate_id"],v_plate["timestamp"],
                #            v_plate["pred_full_length"],v_plate["meas_full_length"],
                #            v_plate["pred_full_cross"],v_plate["meas_full_cross"]))

                v_list.append(v_plate.copy())
                idx += 1

                if idx >= MAX_DISPLAY:
                    break

    v_dict["plate"]=v_list

    return json.dumps(v_dict)

if __name__== '__main__':
    app.run(host="0.0.0.0",port=5000)
